package com.jumei.flume.processor.rules;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.jumei.flume.bo.SensorMessage;
import com.jumei.flume.processor.ProcessorContext;
import com.jumei.flume.common.PageUtils;
import org.apache.commons.collections.MapUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 主T
 *     https://echo.int.jumei.com/issues/156229
 * 
 * @author admin
 *
 */
public class ReferrerRules {

	/**
	 * 事件：
	 * $AppViewScreen&$pageview
	 */
	public final static HashMap<String, TypeResolver2> view_resolvers = new HashMap<String, TypeResolver2>();
	
	static {
		//2 专场
		view_resolvers.put("专场", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("activity");
				t.setSubType(record.getActivity_label_id());

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				return  "Activity".equals( record.getReferrer_page_type() );
			}
			
			public int rank() { //BUG #156830，优先匹配规则12,13；再匹配规则4
				return 12;
			}
			
		});

		//3 店铺
		view_resolvers.put("店铺", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("store");
				t.setSubType(PageUtils.parseStoreId(record.getReferrer()));

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				return  "Store".equals( record.getReferrer_page_type() );
			}
			
			public int rank() { //BUG #156830，优先匹配规则12,13；再匹配规则4
				return 12;
			}
		});

		//4 商品（排除凑团详情页）
		view_resolvers.put("商品（排除凑团详情页）", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("detail");

				String item_id = "";
				try {
					List<String[]> pairs = PageUtils.parseUrlFields(record.getReferrer());
					for (String[] pair : pairs) {
						String key = pair[0];
						String value = pair[1];

						if (key.equalsIgnoreCase("itemid") || key.equalsIgnoreCase("item_id")) {
							item_id = value;
							break;
						}

					}
				} finally {
					//Nothing here
				}
				t.setSubType(item_id);

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				return  "Detail".equals( record.getReferrer_page_type() );
			}
			
			public int rank() { //BUG #156830，优先匹配规则12,13；再匹配规则4
				return 6;
			}
		});

		
		
		//5
		//凑团详情页
		view_resolvers.put("凑团详情页", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				return new Type("coutuan_detail", PageUtils.getItemId(record.getItem_id(), record.getReferrer()));
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				Pattern p = Pattern.compile(
						"jumeimall://page/grouponproduct|http.*jumei.com/(yiqituan/detail[^Secret]|s/coutuan/)");
				boolean matches = Boolean.FALSE;
				if (p.matcher(url).find()) {
					matches = true;
				}
				
				return matches 
						|| "com.jm.android.jumei.GroupDetailActivity".equals(url) 
						|| "JMGrouponDetailViewController".equals(url) ;
			}

			public int rank() { //BUG #156830，优先匹配规则12,13；再匹配规则4
				return 5;
			}
		});
		
		//6
		//凑团现状页
		view_resolvers.put("凑团现状页", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				return new Type("coutuan_status", PageUtils.getItemId(record.getItem_id(), record.getReferrer()));
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				Pattern p = Pattern.compile("jumeimall://page/grouponstatus|http.*jumei.com/yiqituan/detailSecret");
				boolean matches = Boolean.FALSE;
				if (p.matcher(url).find()) {
					matches = true;
				}
				
				return matches;
			}

		});
		
		//5
		//一级频道
		view_resolvers.put("一级频道", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("channel_level_1");
				t.setSubType((String) context.getParameter("pageflag"));

				return t;
			}

			@Override
			public boolean filter(SensorMessage record, ProcessorContext context) {
				if (Strings.isNullOrEmpty(record.getReferrer())) {
					return false;
				}

				Map<String, String> fields = PageUtils.parseUrlFields4Map(record.getReferrer());
				String pageFlag = MapUtils.getString(fields, "pageflag", "");
				context.setParameter("pageflag", pageFlag);

				ArrayList<String> temp = Lists.newArrayList("home_main", "global", "baby_0527", "luxury_pindao",
						"apparel", "accessory", "jiajushuma_pindao", "food_global");
				return record.getReferrer().contains("jumeimall://page/card/index")
						&& temp.contains(pageFlag);
			}
		});

		//6
		//二级频道
		view_resolvers.put("二级频道", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("channel_level_2");
				t.setSubType((String) context.getParameter("pageflag"));

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				if (Strings.isNullOrEmpty(record.getReferrer())) {
					return false;
				}

				Map<String, String> fields = PageUtils.parseUrlFields4Map(record.getReferrer());
				String pageFlag = MapUtils.getString(fields, "pageflag", "");
				context.setParameter("pageflag", pageFlag);

				ArrayList<String> temp = Lists.newArrayList("home_main", "global", "baby_0527", "luxury_pindao",
						"apparel", "accessory", "jiajushuma_pindao", "food_global");
				return record.getReferrer().startsWith("jumeimall://page/card/index") && !temp.contains(pageFlag);
			}
		});

		//频道页icon
//		view_resolvers.put("频道页icon", new TypeResolver2() {
//
//			@Override
//			public Type resolve(SensorMessage record, ProcessorContext context) {
//				return new Type("channel_level_2", record.getPageflag());
//			}
//
//			public boolean filter(SensorMessage record, ProcessorContext context) {
//				ArrayList<String> temp = Lists.newArrayList("home_main", "global", "baby_0527", "luxury_pindao",
//						"apparel", "accessory", "jiajushuma_pindao", "food_global");
//				return record.getUrl().contains("jumeimall://page/card/index") && !temp.contains(record.getPageflag());
//			}
//		});

		//搜索（作为当前页时需排除频道页icon场景）
		view_resolvers.put("搜索（作为当前页时需排除频道页icon场景）", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("search");

				Map<String, String> fields = PageUtils.parseUrlFields4Map(record.getReferrer());
				String postId = MapUtils.getString(fields, "search", "");
				t.setSubType(postId);
				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = PageUtils.getUrlPath(record.getReferrer());
				
				return ( url.endsWith("jumeimall://page/search") ) //#156648: 排除 jumeimall://page/search_home
						|| url.endsWith("jumeimall://page//search")
						|| url.endsWith("jumeimall://page/search/list")
						|| url.endsWith("jumeimall://page/search/search") 
						|| url.equals("JMSearchStoreVC")
						|| ( url.endsWith("jumeimall://page/search/filter") || url.endsWith("jumeimall://page//search/filter"))//BUG #156726
						|| url.endsWith("jumeimall://page/search/list_new")//#159511
						; 
			}
		});

		//帖子详情
		view_resolvers.put("帖子详情", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("tiezi_detail");

				Map<String, String> fields = PageUtils.parseUrlFields4Map(record.getReferrer());
				String postId = MapUtils.getString(fields, "post_id", "");
				t.setSubType(postId);
				
				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				//event="$AppViewScreen" and $url包含jumeimall://page/starpost_detail（明星帖子）或jumeimall://page/newvideo/videodetails（视频帖子）或jumeimall://page/socialdetail（普通图文贴）
				boolean urlMatch = url.contains("jumeimall://page/starpost_detail")
						|| url.contains("jumeimall://page/newvideo/videodetails")
						|| url.contains("jumeimall://page/socialdetail");

				return urlMatch && record.getEvent() .equals(  "$AppViewScreen");
			}
		});

		//12 购物车
		view_resolvers.put("购物车", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("shop_cart_view");

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				return url.equals("JMShopCartViewController")
						|| url.equals("com.jm.android.jumei.buyflow.ShopCarActivity")
						|| url.equals("com.jm.android.jumei.buyflow.activity.shopcar.ShopCarActivity")
						|| url.equals("com.jm.android.jumei.ShopCarActivity") 
//						|| url.contains("cart_h5")
						|| url.equals("JMShopCartGiftController") 
						|| url.equals("JuMeiShopCarViewController")
						|| url.startsWith("jumeimall://page/shopping-cart");
			}
		});

		//注册登录
		view_resolvers.put("注册登录", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("RegisterLogin");

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				return url.equals("JMRegisterLoginBaseViewController");
			}
		});

		//凑团页
		view_resolvers.put("凑团页", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("coutuan");
				t.setSubType("coutuan");

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				return url.contains("jumeimall://page/adcommon");
			}
		});

		//结算中心
		view_resolvers.put("结算中心", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("settlement");
				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				return url.equals("com.jm.android.jumei.usercenter.OrderDetailActivity");
			}
		});

		//扫码
		view_resolvers.put("扫码", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("scan");

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				return url.equals("JMZxingViewController");
			}
		});

		//其他
//		view_resolvers.put("其他", new TypeResolver2() {
//
//			@Override
//			public Type resolve(SensorMessage record, ProcessorContext context) {
//				Type t = new Type();
//				t.setType("other");
//
//				return t;
//			}
//
//			public boolean filter(SensorMessage record, ProcessorContext context) {
//				String url = record.getUrl();
//				return url.contains("other");
//			}
//		});

		//用户中心
		view_resolvers.put("用户中心", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("usercenter");
				t.setSubType("usercenter");

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				return url.equals("jumeimall://page/account");
			}
		});

		//用户中心-浏览记录
		view_resolvers.put("用户中心-浏览记录", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("usercenter_1");
				t.setSubType("browse_history");

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				return url.contains("jumeimall://page/browse-history");
			}
		});

		//用户中心-订单列表
		view_resolvers.put("用户中心-订单列表", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("usercenter_1");
				t.setSubType("order_list");

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				return url.contains("jumeimall://page/account/order/type")
						|| url.contains("jumeimall://page/account/presale");
			}
		});

		//用户中心-订单详情页
		view_resolvers.put("用户中心-订单详情页", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("usercenter_2");
				t.setSubType("order_detail");

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				//jumeimall://page/account/order/detail or JMMyOrderDetailViewController
				return url.contains("jumeimall://page/account/order/detail")
						|| url.equals("JMMyOrderDetailViewController");
			}
		});

		//用户中心-收藏商品
		view_resolvers.put("用户中心-收藏商品", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("usercenter_2");
				t.setSubType("product_list");

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				//jumeimall://page/favorite/product-list，  JMProductCollectionViewController
				return url.contains("jumeimall://page/favorite/product-list")
						|| url.equals("JMProductCollectionViewController");
			}
		});

		//用户中心-收藏品牌
		view_resolvers.put("用户中心-收藏品牌", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("usercenter_2");
				t.setSubType("brand_list");

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				//jumeimall://page/favorite/brand-list， JMBrandCollectionViewController
				return url.contains("jumeimall://page/favorite/brand-list")
						|| url.equals("JMBrandCollectionViewController");
			}
		});

		//用户中心-收藏店铺
		view_resolvers.put("用户中心-收藏店铺", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("usercenter_2");
				t.setSubType("shop_list");

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				//jumeimall://page/favorite/shop-list，JMShopCollectionViewController
				return url.contains("jumeimall://page/favorite/shop-list")
						|| url.equals("JMShopCollectionViewController");
			}
		});

		//用户中心-现金券
		view_resolvers.put("用户中心-现金券", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("usercenter_1");
				t.setSubType("promocard");

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				//jumeimall://page/favorite/shop-list，JMShopCollectionViewController
				return url.contains("http://i.jumei.com/h/promocard/list")||url.contains("jumeimall://page/cash-coupons");
			}
		});
		//用户中心-红包
		view_resolvers.put("用户中心-红包", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("usercenter_1");
				t.setSubType("red_envelope");

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				return url.contains("http://i.jumei.com/h/red_envelope/list")||url.contains("jumeimall://page/red-packet");
			}
		});

		//魔盒-订单列表

		//魔盒-现金券

		//用户中心-聚美余额
		view_resolvers.put("用户中心-聚美余额", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("usercenter_1");
				t.setSubType("balance");//https://echo.int.jumei.com/issues/158624

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				return url.contains("http://i.jumei.com/m/account/balance");
			}
		});

		//用户中心-礼品卡
		view_resolvers.put("用户中心-礼品卡", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("usercenter_1");
				t.setSubType("giftcard");

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = record.getReferrer();
				return url.contains("http://i.jumei.com/m/giftcard/list");
			}
		});
		
		//30 消息中心
		view_resolvers.put("消息中心", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("messagebox");
				
				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				String url = PageUtils.getUrlPath(record.getReferrer());
				return url.endsWith("jumeimall://page/messagebox");
			}
		});
		
		//https://echo.int.jumei.com/issues/157656
		//推荐
		view_resolvers.put("推荐", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("app_tab_video");

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				return record.getReferrer().startsWith("jumeimall://page/newhome?type=video");
			}
		});
		
		
		//关注
		view_resolvers.put("关注", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("app_tab_recommend");

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				return record.getReferrer().startsWith("jumeimall://page/newhome?type=recommend");
			}
		});
		
		//用户中心-作品页

		//作品页（排除用户中心-作品页）
		view_resolvers.put("作品页（排除用户中心-作品页）", new TypeResolver2() {

			@Override
			public Type resolve(SensorMessage record, ProcessorContext context) {
				Type t = new Type();
				t.setType("post_list");

				return t;
			}

			public boolean filter(SensorMessage record, ProcessorContext context) {
				return record.getReferrer().equals("SCUserFansListViewController");
			}
			
			public int rank() {
				return 34;
			}
		});		
	}
	
}
